package src;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.swt.widgets.*;

public class ValidationTextField implements Listener
{
	public static char	k_DECIMAL_SEPARATOR	= '.';

	/**
	 * @wbp.parser.entryPoint
	 */
	@Override
	public void handleEvent(Event e)
	{
		String textOld = ((Text) e.widget).getText();
		String string = e.text;
		char[] chars = new char[string.length()];
		string.getChars(0, chars.length, chars, 0);
		for (int i = 0; i < chars.length; i++)
		{
			if (!('0' <= chars[i] && chars[i] <= '9' || findSubstr(textOld, String.valueOf(k_DECIMAL_SEPARATOR)) <= 1))
			{
				e.doit = false;
				return;
			}
		}

		String text = textOld + string;
		if (text.charAt(0) == k_DECIMAL_SEPARATOR)
		{
			text = '0' + text;
		}
	}

	/**
	 * Determines the number of occurrences of substring in string
	 */
	private int findSubstr(String str, String substr)
	{
		Pattern p = Pattern.compile(substr);
		Matcher m = p.matcher(str);
		int counter = 0;
		while (m.find())
		{
			counter++;
		}
		return counter;
	}

}
